package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * jdk动态代理工厂类
 */
@Component
public class JDKProxyFactory {

    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager manager;

    /**
     * 采用jdk动态代理技术来生成目标类的代理对象
     */
    public  AccountService createAccountSericeJDKProxy(){
        AccountService proxyInstance = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            // o:当前的代理对象引用  method:被调用的目标方法的引用  objects:被调用目标方法所用到的参数
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                Object result = null;
                System.out.println("先执行");
                try {
                    // 手动开启事务:调用事务管理类中的事务开启方法
                    manager.beginTransaction();
                    result = method.invoke(accountService, objects);
                    // 手动提交事务
                    manager.commit();
                } catch (Exception e) {
                    // 手动回滚事务
                    manager.rollback();
                }finally {
                    // 手动释放资源
                    manager.close();
                }
                System.out.println("后执行");
                return result;
            }
        });
        return accountService;
    }
}
